<?php

function test() {
	$protocol = getprotobyname("tcp");
	
	$socket = socket_create(AF_INET, SOCK_STREAM, $protocol);
	if ($socket) {
		$result = socket_bind($socket, "localhost", 1336);
		if ($result) {
			$result = socket_listen($socket, 5);
			if ($result) {
				echo '监听成功!\n';
			} 
		}
	} else {
		echo '监听失败!\n';
	}
	
	do {
		if ($msgsock = socket_accept($socket)) {
			$msg = "=================
					Welcome to the PHP Test Server.
					to quit, type quit.
					to shut down the server type shudown
					to get help message type help.
					=================
					php>";
		}
		
		socket_write($msgsock, $msg, strlen($msg));
		
		do {
			$buf = socket_read($msgsock, 2048, PHP_BINARY_READ);
			
			if ($buf == false) {
				echo "socket_read() failed reason";
				break 2;
			}
			
			if (!$buf = trim($buf)) {
				continue;
			}
			
			if ($buf == 'quit') {
				break;
			}
			
			if ($buf == 'shutdown') {
				socket_close($msgsock);
				break 2;
			}
			
			if ($buf == 'help') {
				$msg = "PHP Server Help Message
						php>";
				socket_write($msgsock, $msg, strlen($msg));
				continue;
			}
			
			$talkback = "PHP: unkwon command ". $buf . "\nphp>";
			
			socket_write($msgsock, $talkback, strlen($talkback));
			echo $buf;
			
		} while (true);
		
		socket_close($msgsock);
	} while (true); 
	
	socket_close($socket);
}

function event_handler($sip) {

	if (empty($sip)) {
		$sip = 'ns';
	}

	$am = astman($sip);

	// $am->Events("call");
	$am->Events("system,call,log");
	//  	$am->add_event_handler('unlink', 'event_default');
	$am->add_event_handler('hangup', 'event_hangup');
	$am->add_event_handler('newchannel', 'event_newchannel');

	// $am->add_event_handler('newcallerid', 'event_default');
	// $am->add_event_handler('newstate', 'event_default');
	// $am->add_event_handler('newexten', 'event_default');
	// $am->add_event_handler('bridge', 'event_default');
	// $am->add_event_handler('bridge', 'event_default');
	// $am->add_event_handler('bridge', 'event_default');
	$am->add_event_handler('Status', 'event_default');
	$am->add_event_handler('Cdr', 'event_default');

	$am->add_event_handler('link', 'event_link');

	while (true) {
		// echo "wait response ...\n";
		echo ".";
		$am->wait_response();
	}

	$am->disconnect();

	logdate($controller, $request);
	return true;
}


function event_hangup($e, $a, $host, $port) {
	echo $e . "\n";

	print_r($a);

	echo sprintf("host = %s, port = %s\n", $host, $port);
}

function event_newchannel($e, $a, $host, $port) {
	echo $e . "\n";

	print_r($a);

	echo sprintf("host = %s, port = %s\n", $host, $port);
}

function event_link($e, $a, $host, $port) {
	echo $e . "\n";

	print_r($a);

	echo sprintf("host = %s, port = %s\n", $host, $port);
}

function event_default($e, $a, $host, $port) {
	echo $e . "\n";

	print_r($a);

	echo sprintf("host = %s, port = %s\n", $host, $port);
}
?>